<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">用户管理</h1>
          <p class="page-subtitle">管理系统用户及其状态信息</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" size="large" @click="handleAddUser">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <div class="search-form">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8" :lg="6">
              <div class="search-item">
                <label class="search-label">用户名</label>
                <el-input
                  v-model="searchForm.username"
                  placeholder="请输入用户名"
                  clearable
                  :prefix-icon="Search"
                />
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :lg="6">
              <div class="search-item">
                <label class="search-label">邮箱地址</label>
                <el-input
                  v-model="searchForm.email"
                  placeholder="请输入邮箱"
                  clearable
                  :prefix-icon="Message"
                />
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :lg="6">
              <div class="search-item">
                <label class="search-label">用户状态</label>
                <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                  <el-option label="全部" value="" />
                  <el-option label="启用" value="active" />
                  <el-option label="禁用" value="inactive" />
                </el-select>
              </div>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="6">
              <div class="search-actions">
                <el-button type="primary" @click="handleSearch" :loading="loading">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-section">
      <el-card class="table-card">
        <el-table
          :data="userList"
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#475569',
            fontWeight: '600',
            fontSize: '14px'
          }"
          :row-style="{ height: '64px' }"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="username" label="用户名" width="140">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar :size="32" :src="row.avatar" class="user-avatar">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <span class="username">{{ row.username }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
          <el-table-column prop="first_name" label="姓名" width="120" />
          <el-table-column prop="is_active" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag 
                :type="row.is_active ? 'success' : 'danger'"
                size="small"
                class="status-tag"
              >
                {{ row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="date_joined" label="创建时间" width="180">
            <template #default="{ row }">
              <div class="time-info">
                <el-icon class="time-icon"><Clock /></el-icon>
                <span>{{ row.date_joined }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" plain @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button
                  size="small"
                  :type="row.is_active ? 'warning' : 'success'"
                  plain
                  @click="handleToggleStatus(row)"
                >
                  <el-icon><component :is="row.is_active ? 'CircleClose' : 'CircleCheck'" /></el-icon>
                  {{ row.is_active ? '禁用' : '启用' }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="600px"
      class="user-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
        label-position="top"
        class="user-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="first_name">
              <el-input v-model="userForm.first_name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dialogType === 'add'">
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="用户状态">
          <el-switch
            v-model="userForm.is_active"
            active-text="启用"
            inactive-text="禁用"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="large" @click="handleSubmit" :loading="submitLoading">
            {{ dialogType === 'add' ? '创建用户' : '保存修改' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Message, Refresh, User, Clock, Edit, CircleClose, CircleCheck } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref<any[]>([])
const loading = ref(false)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const userFormRef = ref()

// 提交加载状态
const submitLoading = ref(false)

// 用户表单
const userForm = reactive({
  id: undefined,
  username: '',
  email: '',
  first_name: '',
  password: '',
  is_active: true
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  first_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      ...searchForm
    }
    
    // 这里应该是实际的 API 调用
    // const response = await userStore.getUsers(params)
    // userList.value = response.results
    // pagination.total = response.count
    
    // 模拟数据
    userList.value = [
      {
        id: 1,
        username: 'admin',
        email: 'admin@example.com',
        first_name: '管理员',
        is_active: true,
        date_joined: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        username: 'user1',
        email: 'user1@example.com',
        first_name: '张三',
        is_active: true,
        date_joined: '2024-01-15 09:15:00'
      },
      {
        id: 3,
        username: 'user2',
        email: 'user2@example.com',
        first_name: '李四',
        is_active: false,
        date_joined: '2024-01-14 16:20:00'
      }
    ]
    pagination.total = 3
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUsers()
}

// 重置
const handleReset = () => {
  searchForm.username = ''
  searchForm.email = ''
  searchForm.status = ''
  handleSearch()
}

// 新增用户
const handleAddUser = () => {
  dialogType.value = 'add'
  userForm.id = undefined
  userForm.username = ''
  userForm.email = ''
  userForm.first_name = ''
  userForm.password = ''
  userForm.is_active = true
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  userForm.id = row.id
  userForm.username = row.username
  userForm.email = row.email
  userForm.first_name = row.first_name
  userForm.password = ''
  userForm.is_active = row.is_active
  dialogVisible.value = true
}

// 切换用户状态
const handleToggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.is_active ? '禁用' : '启用'}该用户吗？`,
      '提示',
      { type: 'warning' }
    )
    
    // 这里应该是实际的 API 调用
    // await userStore.toggleUserStatus(row.id)
    row.is_active = !row.is_active
    ElMessage.success('操作成功')
  } catch (error) {
    console.log('取消操作')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await userFormRef.value.validate()
    
    submitLoading.value = true
    
    if (dialogType.value === 'add') {
      // 这里应该是实际的 API 调用
      // await userStore.createUser(userForm)
      ElMessage.success('用户创建成功')
    } else {
      // 这里应该是实际的 API 调用
      // await userStore.updateUser(userForm.id, userForm)
      ElMessage.success('用户更新成功')
    }
    
    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.log('表单验证失败')
  } finally {
    submitLoading.value = false
  }
}

// 分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchUsers()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchUsers()
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped lang="scss">
.user-management {
  padding: 24px;
  background: transparent;
  min-height: calc(100vh - 64px);

  // 页面头部
  .page-header {
    margin-bottom: 24px;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      padding: 0;

      .title-section {
        .page-title {
          font-size: 28px;
          font-weight: 700;
          color: #1e293b;
          margin: 0 0 8px 0;
          letter-spacing: -0.025em;
        }

        .page-subtitle {
          font-size: 14px;
          color: #64748b;
          margin: 0;
        }
      }

      .header-actions {
        .el-button {
          font-weight: 500;
          border-radius: 8px;
          padding: 12px 24px;
          
          .el-icon {
            margin-right: 6px;
          }
        }
      }
    }
  }

  // 搜索区域
  .search-section {
    margin-bottom: 24px;

    .search-card {
      border-radius: 12px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 20px rgba(0, 0, 0, 0.04);

      .search-form {
        padding: 24px;

        .search-item {
          margin-bottom: 16px;

          .search-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #374151;
            margin-bottom: 8px;
          }

          .el-input,
          .el-select {
            :deep(.el-input__wrapper) {
              border-radius: 8px;
              box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
              border: 1px solid #d1d5db;
              transition: all 0.3s ease;

              &:hover {
                border-color: #9ca3af;
              }

              &.is-focus {
                border-color: #3b82f6;
                box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
              }

              .el-input__inner {
                &::placeholder {
                  color: #9ca3af;
                }
              }
            }
          }
        }

        .search-actions {
          display: flex;
          gap: 12px;
          align-items: flex-end;
          height: 56px;

          .el-button {
            border-radius: 8px;
            font-weight: 500;
            padding: 10px 20px;
            
            .el-icon {
              margin-right: 6px;
            }
          }
        }
      }
    }
  }

  // 主要内容区域
  .content-section {
    .table-card {
      border-radius: 12px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 20px rgba(0, 0, 0, 0.04);
      overflow: hidden;

      :deep(.el-card__body) {
        padding: 0;
      }

      // 表格样式
      .el-table {
        :deep(.el-table__header-wrapper) {
          .el-table__header {
            th {
              border-bottom: 2px solid #e2e8f0;
              
              .cell {
                padding: 16px 12px;
              }
            }
          }
        }

        :deep(.el-table__body-wrapper) {
          .el-table__body {
            tr {
              &:hover {
                background: #f8fafc;
              }

              td {
                border-bottom: 1px solid #f1f5f9;
                
                .cell {
                  padding: 16px 12px;
                }
              }
            }
          }
        }

        // 用户信息样式
        .user-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .user-avatar {
            border: 2px solid #e2e8f0;
            flex-shrink: 0;

            .el-icon {
              color: #9ca3af;
            }
          }

          .username {
            font-weight: 500;
            color: #1e293b;
          }
        }

        // 状态标签样式
        .status-tag {
          border-radius: 6px;
          font-weight: 500;
          padding: 4px 8px;
        }

        // 时间信息样式
        .time-info {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #64748b;
          font-size: 13px;

          .time-icon {
            font-size: 14px;
          }
        }

        // 操作按钮样式
        .action-buttons {
          display: flex;
          gap: 8px;
          justify-content: center;

          .el-button {
            border-radius: 6px;
            font-weight: 500;
            padding: 6px 12px;
            
            .el-icon {
              margin-right: 4px;
            }

            &.el-button--primary {
              &.is-plain {
                &:hover {
                  background: #3b82f6;
                  border-color: #3b82f6;
                  color: white;
                }
              }
            }

            &.el-button--warning {
              &.is-plain {
                &:hover {
                  background: #f59e0b;
                  border-color: #f59e0b;
                  color: white;
                }
              }
            }

            &.el-button--success {
              &.is-plain {
                &:hover {
                  background: #10b981;
                  border-color: #10b981;
                  color: white;
                }
              }
            }
          }
        }
      }

      // 分页样式
      .pagination-wrapper {
        padding: 20px 24px;
        border-top: 1px solid #f1f5f9;
        background: #fafbfc;
        display: flex;
        justify-content: flex-end;

        :deep(.el-pagination) {
          .el-pager {
            li {
              border-radius: 6px;
              margin: 0 2px;
              font-weight: 500;

              &.is-active {
                background: #3b82f6;
                color: white;
              }
            }
          }

          .btn-prev,
          .btn-next {
            border-radius: 6px;
            margin: 0 2px;
          }
        }
      }
    }
  }

  // 对话框样式
  :deep(.user-dialog) {
    .el-dialog__header {
      padding: 24px 24px 0;
      
      .el-dialog__title {
        font-size: 20px;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 0 24px 24px;
    }
  }

  // 表单样式
  .user-form {
    .el-form-item {
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        font-weight: 600;
        color: #374151;
        margin-bottom: 8px;
      }

      .el-input {
        :deep(.el-input__wrapper) {
          border-radius: 8px;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
          border: 1px solid #d1d5db;
          transition: all 0.3s ease;

          &:hover {
            border-color: #9ca3af;
          }

          &.is-focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
          }

          .el-input__inner {
            &::placeholder {
              color: #9ca3af;
            }
          }
        }
      }

      .el-switch {
        :deep(.el-switch__core) {
          border-radius: 12px;
        }
      }
    }
  }

  // 对话框底部
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button {
      border-radius: 8px;
      font-weight: 500;
      padding: 10px 24px;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .user-management {
    .search-section {
      .search-form {
        .search-actions {
          .el-button {
            width: 100%;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .user-management {
    padding: 16px;

    .page-header {
      .header-content {
        flex-direction: column;
        align-items: stretch;
        gap: 16px;

        .title-section {
          .page-title {
            font-size: 24px;
          }
        }

        .header-actions {
          .el-button {
            width: 100%;
            justify-content: center;
          }
        }
      }
    }

    .search-section {
      .search-form {
        padding: 20px;

        .search-item {
          margin-bottom: 16px;
        }

        .search-actions {
          height: auto;
          flex-direction: column;
          
          .el-button {
            width: 100%;
          }
        }
      }
    }

    .content-section {
      .table-card {
        .el-table {
          // 移动端表格样式调整
          .user-info {
            .username {
              font-size: 13px;
            }
          }

          .action-buttons {
            flex-direction: column;
            gap: 4px;

            .el-button {
              font-size: 12px;
              padding: 4px 8px;
            }
          }
        }

        .pagination-wrapper {
          padding: 16px;
          
          :deep(.el-pagination) {
            .el-pagination__total,
            .el-pagination__sizes,
            .el-pagination__jump {
              display: none;
            }
          }
        }
      }
    }

    .user-form {
      .el-row {
        .el-col {
          &:not(:last-child) {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style>